/**
 * Program   :   ServiceInitServiceImpl.java
 * Author    :   shadow guo
 * Create    :   2013-6-24 下午3:46:59
 *
 * Copyright 2008 by Tongfu Information Technology Co. Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information
 * of Tongfu Information Technology Co. Ltd. ("Confidential Information").  You
 * shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement
 * you entered into with Tongfu Information Technology Co. Ltd.
 * 
 */
package com.tongfusoft.example.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletContext;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.tongfusoft.da.help.DBUtils;
import com.tongfusoft.example.data.TDictionary;
import com.tongfusoft.example.data.TDictionaryClass;
import com.tongfusoft.example.data.TSystemparam;
import com.tongfusoft.web.core.Constant;
import com.tongfusoft.web.core.data.DictionaryData;
import com.tongfusoft.web.core.data.SystemParamData;
import com.tongfusoft.web.core.service.IServerInitService;

public class ServiceInitServiceImpl implements IServerInitService{
	/**
	 * Logger for this class
	 */
	private static final Log logger = LogFactory.getLog(ServiceInitServiceImpl.class);

	@Override
	public void initEnv(ServletContext servletContext) {
		//加载字典表和系统参数表内容
		logger.info("server init ......");
		
		List<String> projects = this.getProjectIdList();
		
		servletContext.setAttribute(Constant.DEFAULTPROJECT, this.getDefaultProjectId());
		
		servletContext.setAttribute(Constant.SYSTEMPARAM, this.getSystemParam(projects));
		
		servletContext.setAttribute(Constant.DICTIONARY, this.getDictionary(projects));

		logger.info("......server init");
	}
	
	private String getDefaultProjectId(){
		List<Map<String,String>> list = DBUtils.executeSelect("/loadData#defaultProject", new HashMap());
		if(list != null){
			return list.get(0).get("PROJECT_ID");
		}
		
		return "";
	}
	
	
	private Map<String,Map<String,List<DictionaryData>>> getDictionary(List<String> projects){
		logger.info("load Dictionary Data......");
		Map<String,Map<String,List<DictionaryData>>> dictionaryMap = new HashMap<String,Map<String,List<DictionaryData>>>();
		
		try{
			List<TDictionaryClass> dictClass = DBUtils.executeSelect("/loadData#dictionaryClass", new HashMap());
			
			//填充默认Project
			for(String project : projects){
				Map<String,List<DictionaryData>> dictList = new HashMap<String,List<DictionaryData>>();
				
				for(TDictionaryClass dict : dictClass){
					if(StringUtils.equals(dict.getProjectId(),"0") || StringUtils.equals(dict.getProjectId(), project)){
						dictList.put(dict.getCode(), new ArrayList<DictionaryData>());
					}
				}
				
				dictionaryMap.put(project,dictList);
			}
			
			//填充dictionary
			List<Map<String,Object>> dictionarys = DBUtils.executeSelect("/loadData#dictionary", new HashMap());
			for(Map<String,Object> map : dictionarys){
				TDictionary dict = new TDictionary();
				dict.setDictkeyName((String)map.get("DICTKEY_NAME"));
				dict.setDictkeyValue((String)map.get("DICTKEY_VALUE"));
				dict.setDictclassId((String)map.get("DICTCLASS_ID"));
				dict.setShowOrder(Integer.parseInt(map.get("SHOW_ORDER").toString()));
				
				if(StringUtils.equals((String)map.get("PROJECT_ID"), "0")){
					Iterator<Entry<String,Map<String,List<DictionaryData>>>> iter = dictionaryMap.entrySet().iterator();
					while(iter.hasNext()){
						iter.next().getValue().get(map.get("DICTCLASS_CODE")).add(dict);
					}
				}else{
					dictionaryMap.get(map.get("PROJECT_ID")).get(map.get("DICTCLASS_CODE")).add(dict);
				}
			}
			
		} catch (Exception e){
			logger.error("load Dictionary Data error:" + e.getMessage());
		}
		
		return dictionaryMap;
	}
	
	
	private Map<String,Map<String,SystemParamData>> getSystemParam(List<String> projects){
		logger.info("load System Data......");
		
		Map<String,Map<String,SystemParamData>> paramMap = new HashMap<String,Map<String,SystemParamData>>();
		
		try{
			List<TSystemparam> paramList = DBUtils.executeSelect("/loadData#systemparam", new HashMap());
			
			//默认填充
			for(String project : projects){
				paramMap.put(project, new HashMap<String,SystemParamData>());
			}
			
			//填充数据
			for(TSystemparam param : paramList){
				if(param.getProjectId().equals("0")){ //通用参数
					Iterator<Entry<String,Map<String,SystemParamData>>> iter = paramMap.entrySet().iterator();
					while(iter.hasNext()){
						iter.next().getValue().put(param.getParamCode(), param);
					}
				}else{
					paramMap.get(param.getProjectId()).put(param.getParamCode(), param);
				}
				
			}
			
		} catch (Exception e){
			logger.error("load System Param error:" + e.getMessage());
		}
		
		return paramMap;
	}
	
	private List<String> getProjectIdList(){
		try{
			List<Map<String,Object>> projects = DBUtils.executeSelect("/loadData#project", new HashMap());
			List<String> projectList = new ArrayList<String>();
			
			for(Map<String,Object> project : projects){
				projectList.add((String)project.get("PROJECT_ID"));
			}
			
			return projectList;
		} catch (Exception e){
			logger.error(e.getMessage());
			return Collections.EMPTY_LIST;
		}
	}

}
